package com.aidex.common.core.redis;

import com.aidex.common.utils.ObjectUtils;
import com.aidex.common.utils.reflect.ReflectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * spring redis 工具类
 *
 * @author ruoyi
 **/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class RedisCache {

    @Autowired
    public RedisTemplate redisTemplate;

    @Autowired
    private ValueOperations valueOperations;

    @Autowired
    private HashOperations hashOperations;

    @Autowired
    private ListOperations listOperations;

    @Autowired
    private SetOperations setOperations;

    @Autowired
    private ZSetOperations zSetOperations;

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key   缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout) {
        if (timeout > 0) {
            return expire(key, timeout, TimeUnit.SECONDS);
        }
        return false;
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @param unit    时间单位
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit) {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection) {
        return redisTemplate.delete(collection);
    }

    /**
     * 缓存List数据
     *
     * @param key      缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList) {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 缓存Set
     *
     * @param key     缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext()) {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key) {
        return redisTemplate.opsForHash().entries(key);
    }
    /**
     * 获得缓存的集合
     *
     * @param key
     * @return
     */
    public <T> List<T>  getCacheObjList(final String key) {
        return redisTemplate.opsForHash().values(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key   Redis键
     * @param hKey  Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value) {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 删除map中的数据
     *
     * @param key   Redis键
     * @param hKeys hKeys
     */
    public long deleteCacheMapValue(final String key, final String... hKeys) {
        return redisTemplate.opsForHash().delete(key, hKeys);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key  Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey) {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param key 字符串前缀
     * @return 对象列表
     */
    public Collection<String> getCacheMapKeys(final String key) {
        return redisTemplate.opsForHash().keys(key);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key   Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern) {
        return redisTemplate.keys(pattern);
    }


    /**
     * 获取Hash中的数据
     *
     * @param key  Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey, Callable<T> valueLoader) {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        Object cacheObj = opsForHash.get(key, hKey);
        Object value = null;
        if (cacheObj == null) {
            T call = getCallValue(valueLoader);
            if(null != call){
                value = call;
                redisTemplate.opsForHash().put(key, hKey, value);
                return(T) value;
            }else{
                return null;
            }
        } else {
            return (T) cacheObj;
        }
    }

    /**
     * 动态方法执行
     * @param valueLoader
     * @param <T>
     * @return
     */
    public <T> T getCallValue(Callable<T> valueLoader) {
        try {
            T call = valueLoader.call();
            if (ObjectUtils.isNotEmpty(call)) {
                Field field = ReflectUtils.getField(call.getClass(), "id");
                if (ObjectUtils.isNotEmpty(field) && ObjectUtils.isEmpty(ClassUtils.getMethod(call.getClass(), "id").invoke(call))) {
                    return null;
                }
                return call;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
        return null;
    }


    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    public boolean deleteKey(String... key) {
        if (key != null) {
            int length = key.length;
            if (length > 0) {
                if (length == 1) {
                    return redisTemplate.delete(key[0]);
                } else {
                    return redisTemplate.delete(CollectionUtils.arrayToList(key)) == length;
                }
            }
        }
        return false;
    }

    //============================Value=============================

    public Object get(String key) {
        return StringUtils.isBlank(key) ? null : valueOperations.get(key);
    }

    public String getStringValue(String key) {
        return StringUtils.isBlank(key) ? null : (String) valueOperations.get(key);
    }

    public void set(String key, Object value) {
        valueOperations.set(key, value);
    }

    public void set(String key, Object value, long milliseconds) {
        valueOperations.set(key, value, milliseconds, TimeUnit.MILLISECONDS);
    }

    public long incr(String key) {
        return valueOperations.increment(key);
    }

    public long decr(String key) {
        return valueOperations.decrement(key);
    }

    //================================hash=================================

    public Object hashGet(String key, String item) {
        return hashOperations.get(key, item);
    }

    public Map<Object, Object> hashGetAll(String key) {
        return hashOperations.entries(key);
    }

    public void hmSet(String key, Map<String, Object> map) {
        hashOperations.putAll(key, map);
    }

    public boolean hmSet(String key, Map<String, Object> map, long milliseconds) {
        hmSet(key, map);
        if (milliseconds > 0) {
            return expire(key, milliseconds);
        }
        return false;

    }

    public void hashSet(String key, String item, Object value) {
        hashOperations.put(key, item, value);
    }

    public void hashDelete(String key, Object... item) {
        hashOperations.delete(key, item);
    }

    public boolean hashHasKey(String key, String item) {
        return hashOperations.hasKey(key, item);
    }

    //============================set=============================

    public Set<Object> setMembers(String key) {
        return setOperations.members(key);
    }

    public boolean setIsMember(String key, Object value) {
        return setOperations.isMember(key, value);
    }

    public long setAdd(String key, Object... values) {
        return setOperations.add(key, values);
    }

    public long setAdd(String key, long milliseconds, Object... values) {
        Long count = setOperations.add(key, values);
        if (milliseconds > 0) {
            expire(key, milliseconds);
        }
        return count;
    }

    public long setSize(String key) {
        return setOperations.size(key);
    }

    public long setRemove(String key, Object... values) {
        return setOperations.remove(key, values);
    }

    //===============================list=================================

    public List<Object> lGet(String key, long start, long end) {
        return listOperations.range(key, start, end);
    }

    public long listSize(String key) {
        return listOperations.size(key);
    }

    public Object listIndex(String key, long index) {
        return listOperations.index(key, index);
    }

    public void listRightPush(String key, Object value) {
        listOperations.rightPush(key, value);
    }

    public boolean listRightPush(String key, Object value, long milliseconds) {
        listOperations.rightPush(key, value);
        if (milliseconds > 0) {
            return expire(key, milliseconds);
        }
        return false;
    }

    public long listRightPushAll(String key, List<Object> value) {
        return listOperations.rightPushAll(key, value);
    }

    public boolean listRightPushAll(String key, List<Object> value, long milliseconds) {
        listOperations.rightPushAll(key, value);
        if (milliseconds > 0) {
            return expire(key, milliseconds);
        }
        return false;
    }

    public void listSet(String key, long index, Object value) {
        listOperations.set(key, index, value);
    }

    public long listRemove(String key, long count, Object value) {
        return listOperations.remove(key, count, value);
    }

    //===============================zset=================================

    public boolean zsAdd(String key, Object value, double score) {
        return zSetOperations.add(key, value, score);
    }

}
